package com.sjzd.server.config.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sjzd.server.constant.MailConstants;
import com.sjzd.server.pojo.MailLog;
import com.sjzd.server.service.IMailLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {
   private static final Logger logger = LoggerFactory.getLogger(RabbitMqConfig.class);

   @Autowired
   private ConnectionFactory connectionFactory;
   @Autowired
   private IMailLogService mailLogService;

   @Bean
   public RabbitTemplate rabbitTemplate() {
      RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
      /**
       * 消息确认回调,确认消息是否到达broker
       * correlationData:消息唯一标识
       * ack：确认结果
       * cause：失败原因
       */
      rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
         String msgId = correlationData.getId();
         if (ack) {
            logger.info("消息发送成功===》 {}", msgId);
            UpdateWrapper<MailLog> updateWrapper = new UpdateWrapper<MailLog>().set("status", MailConstants.SUCCESS_SEND)
                    .eq("msgId", msgId);
            mailLogService.update(updateWrapper);
         } else {
           logger.info("消息发送失败===》 {}", msgId);
         }
      });


      /**
       * 消息失败回调，比如router不到queue时回调
       * msg:消息主题
       */
      rabbitTemplate.setReturnsCallback((msg) -> {
         logger.info("消息发送到queue时失败=====> {}",msg.getMessage().getBody());
      });
      return rabbitTemplate;
   }

   @Bean
   public DirectExchange directExchange() {
      return new DirectExchange(MailConstants.EXCHANGE_NAME);
   }

   @Bean
   public Queue queue() {
      return new Queue(MailConstants.QUEUE_NAME, true);
   }

   @Bean
   public Binding binding() {
      return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstants.ROUTER_KEY);
   }
}
